package com.zhaoyd.uaademo.config.security.handler;

import com.zhaoyd.uaademo.core.BaseLogger;
import com.zhaoyd.uaademo.core.ResultData;
import com.zhaoyd.uaademo.util.JsonBeanConvertUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginFailHandler extends BaseLogger implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.warn("auth failed:"+exception.getMessage());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = response.getWriter();
        //FIXME 这里可以解析不同的AuthenticationException，自定义返回结果
        ResultData resultData = ResultData.fail("登录失败:"+exception.getMessage());
        writer.write(JsonBeanConvertUtils.beanToJson(resultData));
        writer.flush();
        writer.close();
    }
}
